import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/**
 * 保持页面状态
 */
class MyApp24 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "ExpansionTileDemo",
      theme: ThemeData.light(),
      home: ExpansionPanelListDemo(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class ExpansionPanelListDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ExpansionPanelListDemoState();
  }
}

class ExpansionPanelListDemoState extends State<ExpansionPanelListDemo> {
  var currentIndex = 0;
  List<int> mList = []; //组成一个int类型数组，用来控制索引
  List<ExpandStateBean> list = [];

  @override
  void initState() {
    for (int i = 0; i < 10; i++) {
      mList.add(i);
      list.add(ExpandStateBean(false, i));
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(" ExpansionPanelListDemo"),
      ),
      body: SingleChildScrollView(
        child: ExpansionPanelList(
          expansionCallback: (index, bol) {
            setCurrentIndex(index, bol);
          },
          children: mList.map((index) {
            return ExpansionPanel(
                headerBuilder: (context, isExpand) {
                  return ListTile(
                    title: Text("head this is $index"),
                  );
                },
                body: ListTile(
                  title: Text("body this is No.$index"),
                ),
                isExpanded: list[index].isOpen);
          }).toList(),
        ),
      ),
    );
  }

  void setCurrentIndex(int index, bool bol) {
    setState(() {
      list.forEach((element) {
        if (element.index == index) {
          element.isOpen = !bol;
        }
      });
    });
  }
}

class ExpandStateBean {
  var isOpen;
  var index;

  ExpandStateBean(this.isOpen, this.index);
}
